# -*- coding:utf-8 -*-

import random
import commands
import shutil
import os

cmd_res = commands.getoutput("service crond status")
print "crontab status :",cmd_res

num = random.randint(1,60)
cron = "%d 1 * * * root /usr/bin/python /data/ops/appinfoclient/bin/start.py report_appinfo\n"%num

def file_update():
    with open("/etc/crontab", "r") as read_f:
        with open('.e.txt.swap', 'w') as write_f:
            for line in read_f:
                if "report_appinfo" in line:
                    line = cron
                write_f.write(line)
    os.remove('/etc/crontab')
    shutil.move('.e.txt.swap','/etc/crontab')

def file_add():
    with open("/etc/crontab","a") as f_w:
        f_w.write(cron)

with open("/etc/crontab", "r") as f:
    for line in f:
        if "report_appinfo" in line:
            file_update()
            print "The crontab of appinfo update success !"
            break
    else:
        file_add()
        print "The crontab of appinfo added success !"
